<template>
	<div class="partner-container">
		<!-- 统计信息 -->
		<div class="stats-bar">
			<div class="stat-item">
				<span class="stat-label">总战力:</span>
				<span class="stat-value">{{ totalPower }}</span>
			</div>
			<div class="stat-item">
				<span class="stat-label">伙伴数量:</span>
				<span class="stat-value">{{ partners.length }}</span>
			</div>
		</div>

		<!-- 筛选栏 -->
		<div class="filter-bar">
			<div class="filter-item" :class="{ active: currentPev === null }" @click="filterByPev(null)">
				<span>全部</span>
			</div>
			<div class="filter-item" :class="{ active: currentPev === 1 }" @click="filterByPev(1)">
				<span>一阶</span>
			</div>
			<div class="filter-item" :class="{ active: currentPev === 2 }" @click="filterByPev(2)">
				<span>二阶</span>
			</div>
			<div class="filter-item" :class="{ active: currentPev === 3 }" @click="filterByPev(3)">
				<span>三阶</span>
			</div>
			<div class="filter-item" :class="{ active: currentPev === 4 }" @click="filterByPev(4)">
				<span>四阶</span>
			</div>
			<div class="filter-item" :class="{ active: currentPev === 5 }" @click="filterByPev(5)">
				<span>五阶</span>
			</div>
		</div>

		<!-- 伙伴列表 - 网格布局 -->
		<div class="partner-grid">
			<div class="partner-card" 
				:class="'card-' + partner.quality"
					v-for="partner in displayedPartners" 
					:key="partner.id" 
					@click="goToDetail(partner.id)">
				<!-- 伙伴名称 -->
				<div class="partner-name">
					<QualityText :quality="partner.pev" :text="partner.name" :bold="true" />
				</div>
				
				<!-- 星级显示 -->
				<div class="star-rating">
					<text class="star" v-for="n in (partner.star || 0)" :key="n">★</text>
				</div>
				
				<div class="partner-stats">
					<span class="stat-label">血</span> {{ partner.attributes.health }} · 
					<span class="stat-label">伤</span> {{ partner.attributes.baseDamage }}
				</div>

				<!-- 状态指示器 -->
				<div class="status-indicator" :class="{ active: partner.is_active }">
					<text>{{ partner.is_active ? '上阵' : '待命' }}</text>
				</div>
			</div>
		</div>

		
		<!-- 全局底部导航栏 -->
		<CustomTabBar />
	</div>
</template>

<script>
import QualityText from '@/components/QualityText.vue'
import api from '@/api'

export default {
	components: {
		QualityText
	},
	data() {
		return {
			partners: [],
			currentPev: null,
			visibleCount: 999, // 全部tab默认显示所有
			loading: false,
			userInfo: {
				nickname: '无名侠客',
				sectName: '无门派',
				coin1: 1000,
				coin2: 50,
				level: 1,
				realm: '练气期'
			}
		}
	},
	computed: {
		filteredPartners() {
			if (this.currentPev === null || this.currentPev === undefined) {
				return this.partners
			}
			return this.partners.filter(partner => partner.pev === this.currentPev)
		},
		displayedPartners() {
			const filtered = this.filteredPartners
			// 如果全部tab，且数量不超过100个，直接显示全部，否则使用分页
			if ((this.currentPev === null || this.currentPev === undefined) && filtered.length <= 100) {
				return filtered
			}
			return filtered.slice(0, this.visibleCount)
		},
		totalPower() {
			return this.partners
				.filter(partner => partner.is_active)
				.reduce((total, partner) => {
					return total + this.calculatePower(partner)
				}, 0)
		}
	},
	mounted() {
		this.loadPartners()
	},
	methods: {
		// 加载伙伴列表
		async loadPartners() {
			if (this.loading) return
			this.loading = true
			try {
				const res = await api.sect.getPartnerList(0)
				if (res && res.code === 1) {
					const raw = res.data || {}
					// 处理按pev分组的数据结构：{"1": [...], "2": [...], ...}
					let list = []
					if (Array.isArray(raw)) {
						list = raw
					} else if (typeof raw === 'object') {
						// 遍历所有键，合并所有品阶的伙伴
						list = Object.keys(raw).reduce((acc, key) => {
							const pevPartners = raw[key] || []
							if (Array.isArray(pevPartners)) {
								return acc.concat(pevPartners)
							}
							return acc
						}, [])
					}
					
					console.log('[伙伴页面] 解析后的伙伴列表:', list.length, '个伙伴')
					
					this.partners = list.map(m => {
						const pev = m.pev != null ? m.pev : 1
						return {
							id: m.partner_id || m.id || 0,
							name: m.name || '未知伙伴',
							avatar: m.avatar || 'default-avatar.svg',
							quality: this.mapQualityToString(pev),
							pev,
							star: m.star || 0,
							is_active: m.is_active || false,
							attributes: {
								baseDamage: m.base_damage ?? (m.attributes?.baseDamage ?? m.attributes?.attack ?? 0),
								defense: m.defense ?? (m.attributes?.defense ?? 0),
								health: m.hp ?? (m.attributes?.health ?? 0),
								speed: m.speed ?? (m.attributes?.speed ?? 0)
							}
						}
					})
					
					console.log('[伙伴页面] 处理后伙伴数量:', this.partners.length)
					console.log('[伙伴页面] 按品阶统计:', this.partners.reduce((acc, p) => {
						acc[p.pev] = (acc[p.pev] || 0) + 1
						return acc
					}, {}))
				} else {
					uni.showToast({ title: (res && res.msg) || '加载失败', icon: 'none' })
				}
			} catch (error) {
				console.error('加载伙伴列表失败:', error)
				if (typeof uni !== 'undefined') {
					uni.showToast({ title: '网络错误', icon: 'none' })
				}
			} finally {
				this.loading = false
			}
		},

		// 按品阶筛选
		filterByPev(pev) {
			this.currentPev = pev
			// 全部tab不需要限制，特定品阶初始显示20个
			if (pev === null || pev === undefined) {
				this.visibleCount = 999 // 全部显示
			} else {
				this.visibleCount = 20 // 特定品阶初始显示20个
			}
			console.log('[伙伴页面] 筛选品阶:', pev === null ? '全部' : pev + '阶', '过滤后数量:', this.filteredPartners.length)
		},

		// 加载更多
		loadMore() {
			// 简单增量渲染以提升性能
			this.visibleCount += 20
		},

		// 处理滚动事件
		handleScroll(e) {
			const { scrollTop, scrollHeight, clientHeight } = e.target
			// 当滚动到底部附近时加载更多
			if (scrollHeight - scrollTop - clientHeight < 100) {
				this.loadMore()
			}
		},

		// 升级伙伴
		async upgradePartner(partnerId) {
			try {
				const response = await uni.request({
					url: `/api/partners/${partnerId}/upgrade`,
					method: 'POST'
				})

				if (response.data.code === 200) {
					uni.showToast({
						title: '升级成功',
						icon: 'success'
					})
					// 更新本地数据
					const index = this.partners.findIndex(p => p.id === partnerId)
					if (index !== -1) {
						this.partners[index] = response.data.data
					}
				} else {
					uni.showToast({
						title: response.data.message || '升级失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('升级伙伴失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			}
		},

		// 升星伙伴
		async starUpPartner(partnerId) {
			try {
				const response = await uni.request({
					url: `/api/partners/${partnerId}/starup`,
					method: 'POST'
				})

				if (response.data.code === 200) {
					uni.showToast({
						title: '升星成功',
						icon: 'success'
					})
					// 更新本地数据
					const index = this.partners.findIndex(p => p.id === partnerId)
					if (index !== -1) {
						this.partners[index] = response.data.data
					}
				} else {
					uni.showToast({
						title: response.data.message || '升星失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('升星伙伴失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			}
		},

		// 跳转到详情页
		goToDetail(partnerId) {
			uni.navigateTo({
				url: `/pages/partner/detail?id=${partnerId}`
			})
		},

		// 跳转到布阵页
		goToFormation() {
			uni.navigateTo({
				url: '/pages/partner/formation'
			})
		},

		// 获取头像URL

		// 获取类型文本
		getTypeText(type) {
			const typeMap = {
				tank: '坦克',
				damage: '输出',
				healer: '治疗',
				control: '控制'
			}
			return typeMap[type] || type
		},

		// 计算战力
		calculatePower(partner) {
			const attributes = partner.attributes;
			const baseDamage = attributes.baseDamage || attributes.attack || 0;
			const defense = attributes.defense || 0;
			const health = attributes.health || 0;
			const speed = attributes.speed || 0;
			return Math.floor((baseDamage * 2 + defense + health * 0.5 + speed) * (1 + partner.star * 0.1));
		},

		// 将品质字符串转换为数字
		getQualityNumber(quality) {
			const qualityMap = {
				'white': 1,
				'green': 2,
				'blue': 3,
				'purple': 4,
				'orange': 5,
				'red': 6
			}
			return qualityMap[quality] || 1
		},
		mapQualityToString(pev) {
			const map = {
				1: 'white',
				2: 'green',
				3: 'blue',
				4: 'purple',
				5: 'orange',
				6: 'red'
			}
			return map[pev] || 'white'
		}
	}
}
</script>

<style scoped>
/* ========== 武侠风格伙伴列表 ========== */
.partner-container {
	min-height: 100vh;
	background: linear-gradient(180deg, #e8dcc4 0%, #d4c4a8 100%);
	padding: 30rpx;
	padding-bottom: 120rpx;
	font-family: "STSong", "Noto Serif SC", serif;
}

/* 用户信息栏已移除 */

/* 招募按钮区域 */
.recruit-section {
	display: flex;
	gap: 24rpx;
	margin-bottom: 40rpx;
}

.recruit-button {
	flex: 1;
	display: flex;
	align-items: center;
	padding: 32rpx 24rpx;
	border-radius: 20rpx;
	color: #ffffff;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
	transition: all 0.3s ease;
	backdrop-filter: blur(10rpx);
	border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.recruit-button.normal-recruit {
	background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.recruit-button.premium-recruit {
	background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.recruit-button:active {
	transform: translateY(2rpx);
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
}

.recruit-icon {
	font-size: 48rpx;
	margin-right: 20rpx;
}

.recruit-text {
	flex: 1;
}

.recruit-title {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 8rpx;
}

.recruit-desc {
	font-size: 26rpx;
	opacity: 0.9;
}

/* 统计信息 - 武侠风格 */
.stats-bar {
	display: flex;
	justify-content: space-between;
	background: rgba(255, 255, 255, 0.95);
	padding: 32rpx;
	border-radius: 20rpx;
	margin-bottom: 40rpx;
	box-shadow: 0 6rpx 20rpx rgba(139, 111, 71, 0.2);
	border: 3rpx solid #c4a57b;
}

.stat-item {
	text-align: center;
	flex: 1;
}

.stat-label {
	font-size: 26rpx;
	color: #8b6f47;
	margin-right: 8rpx;
	font-weight: 600;
}

.stat-value {
	font-size: 36rpx;
	font-weight: bold;
	color: #4a3c2a;
}

/* 筛选栏 */
.filter-bar {
    position: relative;
    display: flex;
    align-items: center;
    margin-bottom: 36rpx;
    padding: 16rpx 20rpx;
    background-color: #f5f0e6;
    background-image: url('/static/images/scroll_texture.svg'),
      radial-gradient(50% 60% at 12% 20%, rgba(0,0,0,0.05), rgba(0,0,0,0) 60%),
      radial-gradient(45% 55% at 85% 75%, rgba(0,0,0,0.04), rgba(0,0,0,0) 65%);
    background-repeat: repeat, no-repeat, no-repeat;
    background-size: 300rpx 300rpx, 100% 100%, 100% 100%;
    background-blend-mode: multiply, normal, normal;
    border-radius: 26rpx;
    box-shadow: 0 6rpx 22rpx rgba(0, 0, 0, 0.12);
    border: 1rpx solid #d9c7a3;
}

.filter-item {
    position: relative;
    z-index: 1;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 56px;
    padding: 14px 12px;
    text-align: center;
    border-radius: 12rpx;
    transition: all 0.3s;
    font-size: 28rpx;
    cursor: pointer;
}

.filter-item.active {
    background: linear-gradient(135deg, #e3d4b4 0%, #cbb287 100%);
    color: #3a2e1a;
    border: 1rpx solid #b08a56;
    box-shadow: 0 4rpx 12rpx rgba(176, 138, 86, 0.35);
}

.filter-item span {
    font-weight: 700;
    letter-spacing: 1rpx;
}

.quality-green { color: #52c41a; }
.quality-blue { color: #1890ff; }
.quality-purple { color: #722ed1; }
.quality-orange { color: #fa8c16; }
.quality-red { color: #ff4d4f; }

/* 伙伴网格布局 - 改为4列，一屏显示20个 */
.partner-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
    margin-bottom: 80px;
    padding: 0 8px;
}

.partner-card {
    background: rgba(255, 255, 255, 0.98);
    border-radius: 10px;
    padding: 10px 8px;
    text-align: center;
    box-shadow: 0 3px 8px rgba(139, 111, 71, 0.2);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
    border: 2px solid #d8c7a3;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 100px;
}

.partner-card:active {
	transform: translateY(-6rpx);
	box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.15);
}

/* 头像已移除，相关样式删除 */

/* 卡片边框更明显（按品质着色） */
.partner-card.card-white { border-color: rgba(255,255,255,0.8); }
.partner-card.card-green { border-color: #52c41a; }
.partner-card.card-blue { border-color: #1890ff; }
.partner-card.card-purple { border-color: #722ed1; }
.partner-card.card-orange { border-color: #fa8c16; }
.partner-card.card-red { border-color: #ff4d4f; }

.partner-card.card-active {
	border-width: 3px;
	box-shadow: 0 4px 12px rgba(139, 111, 71, 0.3);
}

.partner-name {
    font-size: 13px;
    font-weight: 700;
    margin-bottom: 6px;
    line-height: 1.3;
    color: #4a3c2a;
    letter-spacing: 0.3px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.star-rating {
	margin: 4px 0;
	display: flex;
	justify-content: center;
	gap: 2px;
}

.star {
	color: #ffd700;
	font-size: 11px;
	text-shadow: 0.5px 0.5px 1px rgba(0,0,0,0.3);
}

.partner-stats {
    font-size: 13px;
    color: #6b4f3b;
    font-weight: 600;
    margin-bottom: 8px;
    background: rgba(139, 111, 71, 0.08);
    border-radius: 6px;
    padding: 6px 8px;
    border: 1px solid #d8c7a3;
    line-height: 1.4;
}

.stat-label {
	font-weight: 700;
	color: #4a3c2a;
}

.status-indicator {
	padding: 6rpx 12rpx;
	border-radius: 15rpx;
	font-size: 22rpx;
	background-color: #f0f0f0;
	color: #999;
}

.status-indicator.active {
	background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
	color: #333;
}

/* 加载更多 */
.load-more {
	text-align: center;
	padding: 30rpx;
	color: rgba(255, 255, 255, 0.7);
	font-size: 28rpx;
}

/* 底部操作区域 */
.bottom-actions {
	margin-top: 40rpx;
}

.action-card {
	display: flex;
	align-items: center;
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	padding: 32rpx;
	border-radius: 20rpx;
	box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
	border: 1rpx solid rgba(255, 255, 255, 0.3);
	transition: all 0.3s ease;
}

.action-card:active {
	transform: translateY(-4rpx);
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
}

.action-icon {
	font-size: 48rpx;
	margin-right: 24rpx;
}

.action-text {
	flex: 1;
}

.action-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 8rpx;
}

.action-desc {
	font-size: 26rpx;
	color: #666666;
}

/* 响应式设计 */
@media screen and (max-width: 750px) {
	.partner-grid {
		grid-template-columns: repeat(4, 1fr);
		gap: 6px;
		padding: 0 6px;
	}
	
	.partner-card {
		min-height: 95px;
		padding: 8px 6px;
	}
	
	.partner-name {
		font-size: 12px;
	}
	
	.partner-stats {
		font-size: 12px;
		padding: 5px 6px;
	}
	
	.star {
		font-size: 10px;
	}
}

@media screen and (max-width: 600px) {
	.partner-grid {
		grid-template-columns: repeat(2, 1fr);
	}
	
	.currency-display {
		flex-direction: column;
		gap: 10rpx;
	}
	
	.recruit-section {
		flex-direction: column;
	}
}
</style>
.filter-bar::before, .filter-bar::after {
    content: '';
    position: absolute;
    top: 8rpx;
    bottom: 8rpx;
    width: 28rpx;
    border-radius: 14rpx;
    background: linear-gradient(180deg, #d3b88b 0%, #b08a56 100%);
    box-shadow: 0 6rpx 12rpx rgba(0,0,0,0.15);
}

.filter-bar::before { left: -14rpx; }
.filter-bar::after { right: -14rpx; }